import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import get_all_permissions, create_operation_log, get_db_connection

# 权限管理
@web_bp.route('/permissions')
def permissions():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    permissions = get_all_permissions()
    return render_template('permissions.html', permissions=permissions)

# 添加权限
@web_bp.route('/permissions/add', methods=['GET', 'POST'])
def add_permission():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    if request.method == 'POST':
        name = request.form['name']
        code = request.form['code']
        description = request.form['description']
        category = request.form['category']
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('INSERT INTO permissions (name, code, description, category) VALUES (?, ?, ?, ?)',
                          (name, code, description, category))
            conn.commit()
            flash('权限添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', '成功', 0)
        except sqlite3.IntegrityError:
            flash('权限标识符已存在')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'code: {code}', '权限标识符已存在', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.permissions'))
    
    return render_template('add_permission.html')

# 编辑权限
@web_bp.route('/permissions/edit/<int:permission_id>', methods=['GET', 'POST'])
def edit_permission(permission_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    permission = cursor.execute('SELECT * FROM permissions WHERE id=?', (permission_id,)).fetchone()
    conn.close()
    
    if not permission:
        flash('权限不存在')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '编辑权限', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'permission_id: {permission_id}', '权限不存在', 0)
        return redirect(url_for('web.permissions'))
    
    if request.method == 'POST':
        name = request.form['name']
        code = request.form['code']
        description = request.form['description']
        category = request.form['category']
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('''UPDATE permissions SET name=?, code=?, description=?, category=? WHERE id=?''',
                          (name, code, description, category, permission_id))
            conn.commit()
            flash('权限更新成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'permission_id: {permission_id}', '成功', 0)
        except Exception as e:
            flash(f'权限更新失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'permission_id: {permission_id}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.permissions'))
    
    return render_template('edit_permission.html', permission=permission)

# 删除权限
@web_bp.route('/permissions/delete/<int:permission_id>', methods=['POST'])
def delete_permission(permission_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    permission = cursor.execute('SELECT * FROM permissions WHERE id=?', (permission_id,)).fetchone()
    
    if not permission:
        flash('权限不存在')
        conn.close()
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除权限', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'permission_id: {permission_id}', '权限不存在', 0)
        return redirect(url_for('web.permissions'))
    
    try:
        cursor.execute('DELETE FROM permissions WHERE id=?', (permission_id,))
        cursor.execute('DELETE FROM role_permissions WHERE permission_id=?', (permission_id,))
        conn.commit()
        flash('权限删除成功')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除权限', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'permission_id: {permission_id}, code: {permission[2]}', '成功', 0)
    except Exception as e:
        flash(f'权限删除失败: {str(e)}')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除权限', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'permission_id: {permission_id}, code: {permission[2] if permission else "unknown"}', f'失败: {str(e)}', 0)
    finally:
        conn.close()
    
    return redirect(url_for('web.permissions'))